import os
import imp
import sys
import shutil

DEFAULT_IGNORE_PATTERNS = ['*.pyc', '.project', '.pydevproject', '.svn']

def copy_module(moduleName, destinationPath, ignorePatterns=DEFAULT_IGNORE_PATTERNS):
    try:
        moduleFile, modulePath, description = imp.find_module(moduleName)
        moduleType = description[2]
        if moduleType == imp.PKG_DIRECTORY:
            shutil.copytree(modulePath, destinationPath, ignore=shutil.ignore_patterns(*ignorePatterns))
            return modulePath
        elif moduleType == imp.PY_SOURCE or moduleType == imp.PY_COMPILED or moduleType == imp.C_EXTENSION:
            destinationFile = open(os.path.join(destinationPath, os.path.basename(modulePath)), 'w')
            destinationFile.write(moduleFile)
            destinationFile.close()
            moduleFile.close()
        else:
            raise Exception('Unsuported module type')
    finally:
        if moduleFile is not None:
            moduleFile.close()

def get_class_from_name(kls):
    parts = kls.split('.')
    module = '.'.join(parts[:-1])
    m = __import__(module)
    for comp in parts[1:]:
        m = getattr(m, comp)            
    return m

def copy_module_attributes(source_module, destination_module):
    if isinstance(source_module, basestring):
        __import__(source_module)
        source_module = sys.modules[source_module]
    if isinstance(destination_module, basestring):
        __import__(destination_module)
        destination_module = sys.modules[destination_module]
    for name in getattr(source_module, '__all__', dir(source_module)):
        if name[0] != '_':
            setattr(destination_module, name, getattr(source_module, name))

def get_attribute_by_full_name(full_name):        
    p = full_name.rfind('.')
    module_name = full_name[:p]
    attrib_name = full_name[p+1:]
    __import__(module_name)
    return getattr(sys.modules[module_name], attrib_name)
